package com.atguigu.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.atguigu.msm.service.MsmService;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送阿里云短信
     *
     * @param param
     * @param phone
     * @return
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {

        if (StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tK17tXtMHeG9Q7K6FRY", "xkzb2mjtartnAkBva4rYrKrEn0tcY3");
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送的相关参数
//        request.putQueryParameter("RegionId","cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);//要发送的手机号
        request.putQueryParameter("SignName", "阿里云短信测试");//申请的阿里云签名名称
        request.putQueryParameter("TemplateCode", "SMS_154950909");//阿里云 模板Code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));//要发送的验证码

        //发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();

            return success;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }
}
